<template>
  <div class="login-setting">
    <el-form
      ref="userForm"
      :model="userInfo"
      :rules="rules"
      label-width="120px"
      style="margin-left: 120px; margin-top: 30px"
    >
      <el-form-item label="姓名:" prop="username">
        <el-input v-model="userInfo.username" style="width:300px" />
      </el-form-item>

      <el-form-item label="密码:" prop="password">
        <el-input v-model="userInfo.pass" type="password" style="width:300px" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="updateFn">更新</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getUserDetailByIdAPI, saveUserDetailByIdAPI } from '@/api'
export default {
  name: 'LoginSetting',
  data() {
    return {
      userInfo: {
        username: '',
        pass: ''
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getUserDetailByIdFn()
  },
  methods: {
    // 获取员工详情信息
    async getUserDetailByIdFn() {
      const res = await getUserDetailByIdAPI(this.$route.query.id).catch(err => err)
      if (!res.success) return this.$message.error(res.message)
      // 因为更新接口它让我把所有表单对象key+value都带上
      // res.data后台返回的字段叫password, 就不会给pass赋值(没有了回显)
      this.userInfo = { ...res.data, pass: '' }
    },
    // 更新员工信息
    async updateFn() {
      this.$refs.userForm.validate(async valid => {
        if (valid) {
          // if密码框有值->用户要改密码
          if (this.userInfo.pass.trim().length > 0) {
            this.userInfo.password = this.userInfo.pass
          }
          // pass可以带给后台, 如果不想带用delete删除这个属性(但是必须要切换路由页面, 因为你删除数据
          // 上面表单v-model就受到影响了, 所以我决定还是不删除这个属性了, 反正多传一个参数给后台, 后台用不用
          // 后台自己决定)
          const res = await saveUserDetailByIdAPI({
            ...this.userInfo,
            id: this.$route.query.id // 但其实不用传id了，userInfo已经有了，但也没事儿
          })
          this.$message.success(res.message)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
